define(['jquery','api','user','util','text!pages/user/register.html','Vue'],function($,api,user,util){
	var vm,
	   username,
	   wxid,
	   isWx,
	   parentid=$.cookie('parentid'),
	   controller = {
	   init:function(userinfo){
	   	   isWx=util.isWxBrowser();
	   	  
	   	   if(!isWx||userinfo){
	   	   	   this.show(userinfo);
	   	   }else{
	   	   	   util.loadMsg('注册信息努力加载中……');
		       api.isReg({
		           success:function(rs){
		           	    util.loadMsg('');
	                    if(rs.retcode==='0'){
	                    	if(rs.exist=='1'){
			    	    	   util.msg('该微信帐号已注册！');
		                       setTimeout(function(){location.hash='#/'},600);
			    	    	}else{
			    	    	   parentid?controller.show():controller.loadParentId();
			    	    	}
	                    }else{
	                        util.dealErrorCode(rs.retcode);
	                    } 
		   			},
			       error:function(){
			       	   util.loadMsg('');
			           util.msg('系统错误，请联系管理员！');
			       }
		       });
	   	   }	   
	   },
	   show:function(userinfo){
	   	   var  queryObj=util.queryToObj(location.search.substring(1));
	   	   
	   	   wxid=api.getWxid();
	   	   username=$.cookie('nickname');
		   api.footerShow(0);
		   api.setTitle('注册');
	       if(!vm){
		   	 this.render();
		     if(wxid&&username){
		         this.loadCaptcha();
		         this.loadChannels();
		     }
		   }else{
		     vm.show=true;
		     if(wxid)this.loadCaptcha();
		     vm.form.smcode='';
		     vm.form.captcha='';
		     vm.form.username=username;
		     vm.form.weixinid=wxid;
		   }
		   if(userinfo&&queryObj.code){
		   	  this.initUserInfo(queryObj.code);
		   }else if(wxid&&!username){
		      this.loadUserInfo();
		   }
	   },
	   render:function(){
	   	   var that=this;
	   	   $('#pages').append('<div id="register"></div>');
	       require(['text!pages/user/register.html','Vue'],function(tpl,Vue){
	            vm=new Vue({
	               el:'#register',
	               data:{
	               	  show:true,
	               	  isWx:util.isWxBrowser(),
	               	  imgSrc:false,	               	  
	                  form:{
	                  	weixinid:wxid,
	                  	channelid:false,
	                  	username:$.cookie('nickname'),
		                mobile:'',
		                parentid:$.cookie('parentid'),
		                sex:0,
		                usertype:53,//经纪人
		                captcha:'',
		                smcode:'',
		                reloginpwd:'',
		                loginpwd:'',
		                checkbox:true
	                 }
	               },
	               watch:{
		           },
	               methods:{
	                  changeCaptcha:function(){
	                      that.loadCaptcha();
	                  },
	                  getVerify:function(){
						    if(this.form.mobile!=''&&this.form.captcha!=''){
						    	util.Verify.send(this.form.mobile,this.form.captcha,$('#btnVerify1'));
						    }else if(this.form.mobile==''){
						        util.msg('请先输入手机号！');
						    }else if(this.form.captcha==''){
						        util.msg('请先输入验证码！');
						    }
		              },
	                  register:function(){
		              		var data={},
		              		    $subBtn=$('#subBtn');
		              		    
	                        for(var i in this.form){
	                           data[i]=this.form[i];
	                        }
		                	if(that.isValid(data)){
		                		data.agentid=$.cookie('agentid')?$.cookie('agentid'):'';
		                		$subBtn.attr('disabled',true).val('提交中……');
		                		api.register({
		                		   data:data,
		                		   success:function(rs){
		                		     if(rs.retcode=='0'){
		                		        $.cookie('mobile',data.mobile);
		                		    	user.setIsRegister('1');
		                		        location.hash='#/';
		                		    }else{
		                		     	$subBtn.removeAttr("disabled").val('立即注册');
		                		        util.dealErrorCode(rs.retcode);
		                		     }
		                		   },
		                		   error:function(){
		                		     $subBtn.removeAttr("disabled").val('立即注册');
		                		   }
		                		});
		                	}
		              }
	               },
	               template:tpl
	            });
	       })
	   },
	   loadCaptcha:function(){
	       api.captcha(function(rs){
	           if(rs.retcode=='0'){
	               vm.imgSrc='data:image/png;base64,'+rs.imgcode;
	           }
	       })
	   },
	   loadUserInfo:function(){
	       var that=this,
	           cb=function(rs){
    		    	if(rs.retcode==='0'){
    		    	    if(rs.subscribe==='1'){
    		    	     	//处理用户头像
    		    	    	$.cookie('headimgurl',rs.headimgurl);
    		    	    	user.data.headimgurl=rs.headimgurl;
    		    	    	$.cookie('nickname',rs.nickname);
    		    	    	vm.form.username=rs.nickname;
    		    	    	user.data.name=rs.nickname;
    		    	    	$.cookie('subscribe',1);
    		    	    	that.loadCaptcha();
		                    that.loadChannels();
    		    	    }else{
    		    	        that.gotoWx();
    		    	    }
    		    	}else{
    		    	   //util.msg('获取用户信息失败'+rs.retcode);
    		    	   that.gotoWx();
    		    	}
    		   }
    	   api.subscribe(cb);
	   },
	   loadParentId:function(){
	   	   var that=this,
	   	       cb=function(){
	   	          that.show();
	   	       };
	   	   api.appid(function(rs){
	    	  if(rs.retcode=='0'){
	    	     if(rs.appid){
                    $.cookie('appid',rs.appid,{expires:7});
                    $.cookie('parentid',rs.parentid,{expires:7});
                    cb();
	    	     }
	    	  }else if(rs.retcode=='19'){
	    	     util.msg('系统parentid不存在，请联系管理员！');
	    	  }
		   });	
	   },
	   initUserInfo:function(code){
	   	   var that=this;
	   	   api.wxinfo(code,function(rs){
	   	   	    var data;
	   	       if(rs.retcode=='0'){
	   	       	  data=rs.data;
	   	          $.cookie('headimgurl',data.headimgurl);
    	    	  user.data.headimgurl=data.headimgurl;
    	    	  $.cookie('nickname',data.nickname);
    	    	  vm.form.username=data.nickname;
    	    	  vm.form.sex=data.sex;
    	    	  user.data.name=data.nickname;
    	    	  that.loadCaptcha();
		          that.loadChannels();
	   	       }else{
	   	          util.msg('获取用户信息失败,请联系客服人员！');
	   	       }
	   	   });
	   },
	   gotoWx:function(){//去获取页面验证
	   	  var appid=$.cookie('appid'),
		   	  txUrl=function(appid){
	    		var  href='http://'+location.host+'#/user/register/userinfo',
	    		     target=window.wxProxy?(window.wxProxy+'?backUrl='+encodeURIComponent(href)):href;
		    	return 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid+'&redirect_uri='+encodeURIComponent(target)+'&response_type=code&scope=snsapi_userinfo#wechat_redirect'
		      };
		  if(appid){
		      window.location.href=txUrl(appid);
		  }else{
		      api.appid(function(rs){
		    	if(rs.retcode=='0'){
		    	    if(rs.appid){
                        appid=rs.appid;
                        $.cookie('appid',appid,{expires:7});
                        $.cookie('parentid',rs.parentid,{expires:7});
                        window.location.href=txUrl(appid);
		    	    }
		    	  }else if(rs.retcode=='19'){
		    	    util.msg('系统appid不存在，请联系管理员！');
		    	 }
			 });	
		  }
	   },
	   isValid:function(data){
       	  var error=false,
       	      errorHash={
       	           mobile:'请输入手机号！',
       	          'smcode':'请输入验证码！',
       	           password:'请输入登录密码！',
       	           reloginpwd:'请再交输入登录密码！'
       	      };
       	  for(var key in errorHash){
       	  	  if (data[key]=='') {
		          error=errorHash[key];
		          break;
		      }
       	  }
       	  if(!error&&data.loginpwd!==data.reloginpwd){
       	     error="两次输入密码不一致！";
       	  }else if(!error&&!data.checkbox){
       	     error="请确认阅读并同意《风险协议书》！";
       	  }
		  if(error){
		  	  util.msg(error);
		      return false;
		  }else{
		      return true;
		  }
       },
       loadChannels:function(){
       	  var temp=[],
       	      channel;
       	  api.channels(function(rs){
       	     if(rs.retcode=='0'){
       	         for(var i=0;i<rs.data.length;i++){
	   	       	  	   channel=rs.data[i];
	   	       	       temp.push(channel.channelid);
	   	       	  }
	   	       	 vm.form.channelid=temp.join(',');
       	     }else{
       	        
       	     }
       	  })
       },
	   onRouteChange:function(){
	       if(vm)vm.show=false;
	       api.footerShow(1);
	   }
	};
    return controller;
})